package com.flight.view;

import com.flight.model.entity.Cabin;
import com.flight.model.entity.Flight;
import com.flight.util.Constant;
import com.flight.view.components.MessageDialog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.List;

public class BookingPanel extends JPanel {
    private Flight selectedFlight;
    private List<Cabin> cabinList;
    private JRadioButton economyRadio;
    private JRadioButton businessRadio;
    private JButton submitBtn;
    private JLabel priceLabel;
    // 统一字体（解决显示杂乱问题）
    private static final Font DEFAULT_FONT = new Font("微软雅黑", Font.PLAIN, 14);

    public BookingPanel(Flight flight, List<Cabin> cabins) {
        this.selectedFlight = flight;
        this.cabinList = cabins;
        initUI();
        // 绑定默认的提交事件（确保点击有响应）
        bindDefaultSubmitEvent();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10)); // 组件间距10px
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); // 外边框留白
        setFont(DEFAULT_FONT);

        // 1. 航班信息面板（顶部）
        JPanel flightInfoPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        flightInfoPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                "航班信息",
                0, 0,
                DEFAULT_FONT,
                Color.BLUE
        ));
        // 航班信息标签使用统一字体
        JLabel flightNoLabel = new JLabel("航班号：");
        JLabel depCityLabel = new JLabel("出发地：");
        JLabel arrCityLabel = new JLabel("目的地：");
        flightNoLabel.setFont(DEFAULT_FONT);
        depCityLabel.setFont(DEFAULT_FONT);
        arrCityLabel.setFont(DEFAULT_FONT);

        JLabel flightNoValue = new JLabel(selectedFlight.getFlightNo());
        JLabel depCityValue = new JLabel(selectedFlight.getDepartureCity());
        JLabel arrCityValue = new JLabel(selectedFlight.getArrivalCity());
        flightNoValue.setFont(DEFAULT_FONT);
        depCityValue.setFont(DEFAULT_FONT);
        arrCityValue.setFont(DEFAULT_FONT);

        flightInfoPanel.add(flightNoLabel);
        flightInfoPanel.add(flightNoValue);
        flightInfoPanel.add(depCityLabel);
        flightInfoPanel.add(depCityValue);
        flightInfoPanel.add(arrCityLabel);
        flightInfoPanel.add(arrCityValue);
        add(flightInfoPanel, BorderLayout.NORTH);

        // 2. 舱位选择面板（中间）
        JPanel cabinPanel = new JPanel();
        cabinPanel.setLayout(new BoxLayout(cabinPanel, BoxLayout.Y_AXIS)); // 垂直排列
        cabinPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                "选择舱位",
                0, 0,
                DEFAULT_FONT,
                Color.BLUE
        ));
        cabinPanel.setPreferredSize(new Dimension(0, 150)); // 固定高度，避免拉伸

        // 单选按钮组
        ButtonGroup cabinGroup = new ButtonGroup();
        economyRadio = new JRadioButton("经济舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) + "）");
        businessRadio = new JRadioButton("商务舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) + "）");
        // 设置单选按钮样式
        economyRadio.setFont(DEFAULT_FONT);
        businessRadio.setFont(DEFAULT_FONT);
        economyRadio.setAlignmentX(LEFT_ALIGNMENT); // 左对齐
        businessRadio.setAlignmentX(LEFT_ALIGNMENT);
        cabinGroup.add(economyRadio);
        cabinGroup.add(businessRadio);

        // 价格标签（与单选按钮对齐）
        priceLabel = new JLabel();
        priceLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        priceLabel.setForeground(Color.RED); // 价格红色突出
        priceLabel.setAlignmentX(LEFT_ALIGNMENT);
        priceLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)); // 顶部留白

        // 添加组件到舱位面板（带间距）
        cabinPanel.add(Box.createVerticalStrut(10)); // 顶部留白
        cabinPanel.add(economyRadio);
        cabinPanel.add(Box.createVerticalStrut(10)); // 按钮间距
        cabinPanel.add(businessRadio);
        cabinPanel.add(Box.createVerticalStrut(10));
        cabinPanel.add(priceLabel);
        add(cabinPanel, BorderLayout.CENTER);

        // 3. 提交按钮面板（底部）
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        submitBtn = new JButton("提交订单");
        submitBtn.setFont(DEFAULT_FONT);
        submitBtn.setPreferredSize(new Dimension(120, 35)); // 按钮大小
        btnPanel.add(submitBtn);
        add(btnPanel, BorderLayout.SOUTH);

        // 初始化选中状态和价格
        initCabinSelection();
    }

    // 初始化舱位选中状态和价格
    private void initCabinSelection() {
        if (getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) > 0) {
            economyRadio.setSelected(true);
            updatePriceLabel(Constant.CABIN_TYPE_ECONOMY);
        } else if (getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) > 0) {
            businessRadio.setSelected(true);
            updatePriceLabel(Constant.CABIN_TYPE_BUSINESS);
        } else {
            priceLabel.setText("当前航班无可用舱位");
            submitBtn.setEnabled(false); // 无票时禁用按钮
        }

        // 绑定单选按钮事件（切换舱位更新价格）
        economyRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_ECONOMY));
        businessRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_BUSINESS));
    }

    // 更新价格标签
    private void updatePriceLabel(String cabinType) {
        Cabin cabin = getCabinByType(cabinType);
        if (cabin != null) {
            priceLabel.setText("价格：" + cabin.getCabinPrice() + "元");
        } else {
            priceLabel.setText("该舱位不存在");
        }
    }

    // 绑定默认的提交订单事件（确保点击有响应）
    private void bindDefaultSubmitEvent() {
        submitBtn.addActionListener(e -> {
            if (checkCabinValid()) {
                // 这里只是示例反馈，实际项目需调用订单服务创建订单
                Cabin selectedCabin = getSelectedCabin();
                String message = String.format(
                        "订单提交成功！\n航班：%s\n舱位：%s\n价格：%s元",
                        selectedFlight.getFlightNo(),
                        selectedCabin.getCabinType(),
                        selectedCabin.getCabinPrice()
                );
                MessageDialog.showInfo(this, message);
                // 关闭当前窗口（如果需要）
                Window window = SwingUtilities.getWindowAncestor(this);
                if (window != null) {
                    window.dispose();
                }
            }
        });
    }



    /**
     * 根据舱位类型获取余票
     */
    private int getCabinRemaining(String cabinType) {
        Cabin cabin = getCabinByType(cabinType);
        return cabin != null ? cabin.getRemainingSeats() : 0;
    }

    /**
     * 内部工具：根据类型查找舱位
     */
    private Cabin getCabinByType(String cabinType) {
        // 避免 cabinList 为 null 导致的空指针（额外防御）
        if (cabinList == null) {
            return null;
        }
        for (Cabin cabin : cabinList) {
            if (cabin != null && cabin.getCabinType().equals(cabinType)) {
                return cabin;
            }
        }
        return null;
    }

    /**
     * 绑定提交订单按钮事件
     */
    public void addSubmitListener(ActionListener listener) {
        submitBtn.addActionListener(listener);
    }


    /**
     //     * 根据舱位类型获取舱位对象
     //     */
    public Cabin getSelectedCabin() {
        if (economyRadio.isSelected()) {
            return getCabinByType(Constant.CABIN_TYPE_ECONOMY);
        } else if (businessRadio.isSelected()) {
            return getCabinByType(Constant.CABIN_TYPE_BUSINESS);
        }
        return null;
    }
    /**
     * 校验选中的舱位是否有票
     */
    public boolean checkCabinValid() {
        Cabin cabin = getSelectedCabin();
        if (cabin == null) {
            MessageDialog.showError(this, "请选择舱位");
            return false;
        }
        if (cabin.getRemainingSeats() < 1) {
            MessageDialog.showError(this, cabin.getCabinType() + "已无余票");
            return false;
        }
        return true;
    }

    /**
     * 获取当前选中的航班
     */
    public Flight getSelectedFlight() {
        return selectedFlight;
    }
}


//package com.flight.view;
//
//import com.flight.model.entity.Cabin;
//import com.flight.model.entity.Flight;
//import com.flight.util.Constant;
//import com.flight.view.components.MessageDialog;
//import javax.swing.*;
//import java.awt.*;
//import java.awt.event.ActionListener;
//import java.util.List;
//
///**
// * 订票面板（选择舱位并提交订单）
// */
//public class BookingPanel extends JPanel {
//    private Flight selectedFlight; // 当前选中的航班
//    private List<Cabin> cabinList; // 该航班的舱位列表
//    private JRadioButton economyRadio; // 经济舱选择
//    private JRadioButton businessRadio; // 商务舱选择
//    private JButton submitBtn; // 提交订单按钮
//    private JLabel priceLabel; // 显示选中舱位的价格
//
//    public BookingPanel(Flight flight, List<Cabin> cabins) {
//        this.selectedFlight = flight;
//        this.cabinList = cabins;
//        initUI();
//    }
//
//    private void initUI() {
//        setLayout(new BorderLayout());
//        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
//
//        // 航班信息面板（顶部）
//        JPanel flightInfoPanel = new JPanel(new GridLayout(3, 2, 10, 10));
//        flightInfoPanel.setBorder(BorderFactory.createTitledBorder("航班信息"));
//        flightInfoPanel.add(new JLabel("航班号："));
//        flightInfoPanel.add(new JLabel(selectedFlight.getFlightNo()));
//        flightInfoPanel.add(new JLabel("出发地："));
//        flightInfoPanel.add(new JLabel(selectedFlight.getDepartureCity()));
//        flightInfoPanel.add(new JLabel("目的地："));
//        flightInfoPanel.add(new JLabel(selectedFlight.getArrivalCity()));
//        add(flightInfoPanel, BorderLayout.NORTH);
//
//        // 舱位选择面板（中间）
//        JPanel cabinPanel = new JPanel(new GridLayout(3, 1, 10, 10));
//        cabinPanel.setBorder(BorderFactory.createTitledBorder("选择舱位"));
//
//        // 单选按钮组（经济舱/商务舱）
//        ButtonGroup cabinGroup = new ButtonGroup();
//        economyRadio = new JRadioButton("经济舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) + "）");
//        businessRadio = new JRadioButton("商务舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) + "）");
//        cabinGroup.add(economyRadio);
//        cabinGroup.add(businessRadio);
//
//        // 关键修复：先实例化 priceLabel，再调用 updatePriceLabel
//        priceLabel = new JLabel(); // 提前实例化，避免 null
//
//        // 默认选中舱位并更新价格（此时 priceLabel 已实例化）
//        if (getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) > 0) {
//            economyRadio.setSelected(true);
//            updatePriceLabel(Constant.CABIN_TYPE_ECONOMY);
//        } else if (getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) > 0) {
//            businessRadio.setSelected(true);
//            updatePriceLabel(Constant.CABIN_TYPE_BUSINESS);
//        } else {
//            priceLabel.setText("当前航班无可用舱位"); // 处理无票情况
//        }
//
//        // 添加组件到面板
//        cabinPanel.add(economyRadio);
//        cabinPanel.add(businessRadio);
//        cabinPanel.add(priceLabel);
//        add(cabinPanel, BorderLayout.CENTER);
//
//        // 绑定单选按钮事件（更新价格）
//        economyRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_ECONOMY));
//        businessRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_BUSINESS));
//
//        // 提交按钮（底部）
//        JPanel btnPanel = new JPanel();
//        submitBtn = new JButton("提交订单");
//        btnPanel.add(submitBtn);
//        add(btnPanel, BorderLayout.SOUTH);
//    }
//
//    /**
//     * 更新价格标签（显示选中舱位的价格）
//     */
//    private void updatePriceLabel(String cabinType) {
//        Cabin cabin = getCabinByType(cabinType);
//        if (cabin != null) {
//            priceLabel.setText("价格：" + cabin.getCabinPrice() + "元");
//        } else {
//            priceLabel.setText("该舱位不存在"); // 处理异常情况
//        }
//    }
//
//    /**
//     * 根据舱位类型获取余票
//     */
//    private int getCabinRemaining(String cabinType) {
//        Cabin cabin = getCabinByType(cabinType);
//        return cabin != null ? cabin.getRemainingSeats() : 0;
//    }
//
//    /**
//     * 根据舱位类型获取舱位对象
//     */
//    public Cabin getSelectedCabin() {
//        if (economyRadio.isSelected()) {
//            return getCabinByType(Constant.CABIN_TYPE_ECONOMY);
//        } else if (businessRadio.isSelected()) {
//            return getCabinByType(Constant.CABIN_TYPE_BUSINESS);
//        }
//        return null;
//    }
//
//    /**
//     * 内部工具：根据类型查找舱位
//     */
//    private Cabin getCabinByType(String cabinType) {
//        // 避免 cabinList 为 null 导致的空指针（额外防御）
//        if (cabinList == null) {
//            return null;
//        }
//        for (Cabin cabin : cabinList) {
//            if (cabin != null && cabin.getCabinType().equals(cabinType)) {
//                return cabin;
//            }
//        }
//        return null;
//    }
//
//    /**
//     * 绑定提交订单按钮事件
//     */
//    public void addSubmitListener(ActionListener listener) {
//        submitBtn.addActionListener(listener);
//    }
//
//    /**
//     * 校验选中的舱位是否有票
//     */
//    public boolean checkCabinValid() {
//        Cabin cabin = getSelectedCabin();
//        if (cabin == null) {
//            MessageDialog.showError(this, "请选择舱位");
//            return false;
//        }
//        if (cabin.getRemainingSeats() < 1) {
//            MessageDialog.showError(this, cabin.getCabinType() + "已无余票");
//            return false;
//        }
//        return true;
//    }
//
//    /**
//     * 获取当前选中的航班
//     */
//    public Flight getSelectedFlight() {
//        return selectedFlight;
//    }
//}
//
//
////package com.flight.view;
////
////import com.flight.model.entity.Cabin;
////import com.flight.model.entity.Flight;
////import com.flight.util.Constant;
////import com.flight.view.components.MessageDialog;
////import javax.swing.*;
////import java.awt.*;
////import java.awt.event.ActionListener;
////import java.util.List;
////
/////**
//// * 订票面板（选择舱位并提交订单）
//// */
////public class BookingPanel extends JPanel {
////    private Flight selectedFlight; // 当前选中的航班
////    private List<Cabin> cabinList; // 该航班的舱位列表
////    private JRadioButton economyRadio; // 经济舱选择
////    private JRadioButton businessRadio; // 商务舱选择
////    private JButton submitBtn; // 提交订单按钮
////    private JLabel priceLabel; // 显示选中舱位的价格
////
////    public BookingPanel(Flight flight, List<Cabin> cabins) {
////        this.selectedFlight = flight;
////        this.cabinList = cabins;
////        initUI();
////    }
////
////    private void initUI() {
////        setLayout(new BorderLayout());
////        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
////
////        // 航班信息面板（顶部）
////        JPanel flightInfoPanel = new JPanel(new GridLayout(3, 2, 10, 10));
////        flightInfoPanel.setBorder(BorderFactory.createTitledBorder("航班信息"));
////        flightInfoPanel.add(new JLabel("航班号："));
////        flightInfoPanel.add(new JLabel(selectedFlight.getFlightNo()));
////        flightInfoPanel.add(new JLabel("出发地："));
////        flightInfoPanel.add(new JLabel(selectedFlight.getDepartureCity()));
////        flightInfoPanel.add(new JLabel("目的地："));
////        flightInfoPanel.add(new JLabel(selectedFlight.getArrivalCity()));
////        add(flightInfoPanel, BorderLayout.NORTH);
////
////        // 舱位选择面板（中间）
////        JPanel cabinPanel = new JPanel(new GridLayout(3, 1, 10, 10));
////        cabinPanel.setBorder(BorderFactory.createTitledBorder("选择舱位"));
////
////        // 单选按钮组（经济舱/商务舱）
////        ButtonGroup cabinGroup = new ButtonGroup();
////        economyRadio = new JRadioButton("经济舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) + "）");
////        businessRadio = new JRadioButton("商务舱（余票：" + getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) + "）");
////        cabinGroup.add(economyRadio);
////        cabinGroup.add(businessRadio);
////
////        // 默认选中经济舱（如果有票）
////        if (getCabinRemaining(Constant.CABIN_TYPE_ECONOMY) > 0) {
////            economyRadio.setSelected(true);
////            updatePriceLabel(Constant.CABIN_TYPE_ECONOMY);
////        } else if (getCabinRemaining(Constant.CABIN_TYPE_BUSINESS) > 0) {
////            businessRadio.setSelected(true);
////            updatePriceLabel(Constant.CABIN_TYPE_BUSINESS);
////        }
////
////        // 价格显示
////        priceLabel = new JLabel();
////        cabinPanel.add(economyRadio);
////        cabinPanel.add(businessRadio);
////        cabinPanel.add(priceLabel);
////        add(cabinPanel, BorderLayout.CENTER);
////
////        // 绑定单选按钮事件（更新价格）
////        economyRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_ECONOMY));
////        businessRadio.addActionListener(e -> updatePriceLabel(Constant.CABIN_TYPE_BUSINESS));
////
////        // 提交按钮（底部）
////        JPanel btnPanel = new JPanel();
////        submitBtn = new JButton("提交订单");
////        btnPanel.add(submitBtn);
////        add(btnPanel, BorderLayout.SOUTH);
////    }
////
////    /**
////     * 更新价格标签（显示选中舱位的价格）
////     */
////    private void updatePriceLabel(String cabinType) {
////        Cabin cabin = getCabinByType(cabinType);
////        if (cabin != null) {
////            priceLabel.setText("价格：" + cabin.getCabinPrice() + "元");
////        }
////    }
////
////    /**
////     * 根据舱位类型获取余票
////     */
////    private int getCabinRemaining(String cabinType) {
////        Cabin cabin = getCabinByType(cabinType);
////        return cabin != null ? cabin.getRemainingSeats() : 0;
////    }
////
////    /**
////     * 根据舱位类型获取舱位对象
////     */
////    public Cabin getSelectedCabin() {
////        if (economyRadio.isSelected()) {
////            return getCabinByType(Constant.CABIN_TYPE_ECONOMY);
////        } else if (businessRadio.isSelected()) {
////            return getCabinByType(Constant.CABIN_TYPE_BUSINESS);
////        }
////        return null;
////    }
////
////    /**
////     * 内部工具：根据类型查找舱位
////     */
////    private Cabin getCabinByType(String cabinType) {
////        for (Cabin cabin : cabinList) {
////            if (cabin.getCabinType().equals(cabinType)) {
////                return cabin;
////            }
////        }
////        return null;
////    }
////
////    /**
////     * 绑定提交订单按钮事件
////     */
////    public void addSubmitListener(ActionListener listener) {
////        submitBtn.addActionListener(listener);
////    }
////
////    /**
////     * 校验选中的舱位是否有票
////     */
////    public boolean checkCabinValid() {
////        Cabin cabin = getSelectedCabin();
////        if (cabin == null) {
////            MessageDialog.showError(this, "请选择舱位");
////            return false;
////        }
////        if (cabin.getRemainingSeats() < 1) {
////            MessageDialog.showError(this, cabin.getCabinType() + "已无余票");
////            return false;
////        }
////        return true;
////    }
////
////    /**
////     * 获取当前选中的航班
////     */
////    public Flight getSelectedFlight() {
////        return selectedFlight;
////    }
////}